package com.qf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {
    @RequestMapping("/test1")
    public void test1(MultipartFile file, HttpServletRequest request) throws IOException {
        System.out.println("0000");
//        1 获取保存的路径   a.jpg
        String realPath = request.getServletContext().getRealPath("/upload");
        ServletContext servletContext = request.getServletContext();
        System.out.println(servletContext + "    000");
        System.out.println(realPath);

//        2 获取原文件的名称
        String filename = file.getOriginalFilename();
        System.out.println(filename);

//        3为每一个 上传的文件生成 唯一的文件名
        String uuid = UUID.randomUUID().toString().replaceAll("_", "");
        System.out.println(uuid);

//        4 将UUID 和源文件 名称 拼接在一起
        String newFileName = uuid + "_" + filename;
//         5   保存文件
        file.transferTo(new File(realPath + File.separator + newFileName));


    }
}
